package com.converter.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import com.converter.bean.Dept;
import com.converter.mapper.SysDeptMapper;
import com.converter.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl implements DeptService {

	@Autowired
	private SysDeptMapper deptMapper;

	@Override
	public int addDept(Dept dept) {
		return deptMapper.insertDept(dept);
	}

	@Override
	public int deleteDept(Long deptId) {
		Long[] deptIds = selecteDeptList(deptId);
		return deptMapper.deleteDept(deptIds);
	}

	@Override
	public int updateDept(Dept dept) {
		return deptMapper.updateDept(dept);
	}

	@Override
	public List<Dept> selecteDeptList(Dept dept) {
		List<Dept> list = deptMapper.selecteDeptList(dept);
		List<Dept> result = buildTree(list);
		return result;
	}

	@Override
	public List<Dept> getDeptList(Dept dept) {
		return deptMapper.selecteDeptList(dept);
	}

	@Override
	public Long[] selecteDeptList(Long deptId) {
		Dept dept = new Dept();
		List<Dept> list = deptMapper.selecteDeptList(dept);
		List<Dept> result = buildTree(list);
		List<Long> arr = new ArrayList<Long>();
		if(deptId == 0) {
			for (Dept d : list) {
				arr.add(d.getId());
			}
		}else {
			traverse(result, deptId,false,arr);
		}
		return arr.toArray(new Long[arr.size()]);
	}

	public static void main(String[] args) {
		List<Long> arr = new ArrayList<Long>();
		arr.add(1L);
		arr.add(2L);
		arr.add(3L);
		Long[] a = arr.toArray(new Long[arr.size()]);
		System.out.println(a[2]);
	}


	/**
	 * 将列表状态的部门组装成树结构部门
	 * @param list 部门列表
	 * @return
	 */
	private List<Dept> buildTree(List<Dept> list){
		List<Dept> result = new ArrayList<>();
		Map<Long,Dept> temp = new HashMap<>();
		for (Dept d : list) {
		   if(d.getParentId() == 0) {//根节点
			   result.add(d);
		   }
		   temp.put(d.getId(), d);
		}
		for (Dept d : list) {
			if(d.getParentId() != 0) {
				Dept parent = temp.get(d.getParentId());
				List<Dept> children = parent.getChildren();
				if(children == null ) {
					children = new ArrayList<Dept>();
					parent.setChildren(children);
				}
				d.setParentName(parent.getName());
				children.add(d);
			}
		}
		return result;
	}

	/**
	 * 遍历树查找满足科室ID的下级部门包括本级
	 * @param list
	 * @param deptId
	 * @param isSubDept
	 * @param arr
	 */
	private void traverse(List<Dept> list,Long deptId,boolean isSubDept,List<Long> arr) {
		if(list != null && list.size() > 0) {
			for (Dept d : list) {
				if(d.getId().longValue() == deptId.longValue() || isSubDept) {
					arr.add(d.getId());
					traverse(d.getChildren(),deptId,true,arr);
				}else {
					traverse(d.getChildren(),deptId,false,arr);
				}
			}
		}
	}
}
